#--
# Copyright (c) 2007 Mathew Abonyi
# Please read LICENSE document for more information.
#++

module Retrospectiva
  module Extension
    module SCMTicketUpdate

      # This extension to the Changeset model translates SCM ticket
      # updates into actual changes on each referenced ticket.
      module ChangesetExtension

        def self.included(base)
          base.class_eval do
            include InstanceMethods
            after_create :update_tickets_from_references
          end
        end

        module InstanceMethods

          def update_tickets_from_references
            changes_to_integrate = Update.new(self.author, self.log)
            ticket_includes = [:milestone, { :project => [:milestones, {:groups => :users}, {:ticket_property_types => :ticket_properties}] }]
            changes_to_integrate.each_reference do |ticket_reference|
              begin
                ticket = Ticket.find(ticket_reference.id, :include => ticket_includes)
                ticket.update_from_reference(ticket_reference)

                change = TicketChange.new_from_ticket(ticket)
                change.author = self.author
                change.content = ticket_reference.content

                unless change.blank?
                  TicketChange.without_spam_check { change.save! }
                  ticket.save!
                end
              rescue ActiveRecord::ActiveRecordError => e
                logger.debug "[SCM Ticket Update] Exception!\n#{e.inspect}\n" + e.backtrace.join("\n")
                logger.error "[SCM Ticket Update] Could not integrate reference to ##{ticket_reference.id}"
              end
            end
          end

        end
      end
    end
  end
end

Changeset.send(:include, Retrospectiva::Extension::SCMTicketUpdate::ChangesetExtension)
